package pinyinJava.persistence;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import pinyinJava.bean.DBean;
import pinyinJava.executors.Sim2TraExecutor;

import java.io.*;
import java.util.ArrayList;

public class FilePer implements IFilePersistence {

    @Override
    public void save(String path, ArrayList<DBean> dList) throws IOException {
        String json = new Gson().toJson(dList);
        File file = new File(path);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file, false);
        fileOutputStream.write(json.getBytes("utf-8"));
        fileOutputStream.close();
    }

    @Override
    public ArrayList<DBean> read(String path) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
        String json = reader.readLine();
        reader.close();
        System.out.println(path);
        json = new Sim2TraExecutor().execute(json);
        return new Gson().fromJson(json, new TypeToken<ArrayList<DBean>>() {
        }.getType());
    }
}
